<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Index_Login extends Controller_Index_Base
{
    public function action_register()
    {
        if (HTTP_Request::POST == $this->request->method()) {
            $email     = $this->request->post('email');
            $site      = $this->request->post('site'); 
            $password  = $this->request->post('password');
            $redirect_url = $this->request->post('redirect_url');
            $utm_marks = $this->request->post('utm_marks'); 
                  
            try {
                $user = ORM::factory('user')->add_user($email, $password, 50, $site, $utm_marks);                               
                $_POST = array();
                 
                Model_Auth::instance()->login($email, $password, true);
                
                $url = '/my';
                if ($redirect_url) {
                    $url = $redirect_url;    
                }                     
                Request::current()->redirect($url); 
            } catch (Model_Exception $e) {
                $message = $e->getMessage();
                if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
                    $message = 'Данный email уже зарегистрирован';
                }
            }
        }
                
        $content = new View('index/login/register_tpl');        
        $this->print_template('Регистрация', $content);
    }
    
    public function action_login()
    {           
         if (HTTP_Request::POST == $this->request->method()) {
            $email    = $this->request->post('email');
            $password = $this->request->post('password');
            $redirect_url = $this->request->post('redirect_url');
                  
            try {
                Model_Auth::instance()->login($email, $password, true);                
                $_POST = array(); 
                if (Model_Auth::instance()->logged_in()) {
                    $url = '/my';
                    if ($redirect_url) {
                        $url = $redirect_url;    
                    }
                    Request::current()->redirect($url);    
                }                        
            } catch (Model_Exception $e) {
                //$this->add_message($e->getMessage());
            }
        }
        $content = new View('index/login/login_tpl');       
        $this->print_template('Авторизация', $content);
    }
    
    public function action_logout()
    {
        Model_Auth::instance()->logout();
        Request::current()->redirect($_SERVER['HTTP_REFERER']);   
    }
} 
